//
//  AVGOAuthViewController.swift
//  33-
//
//  Created by mac on 16/7/22.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import  SVProgressHUD
class AVGOAuthViewController: UIViewController {
    
    override func loadView() {
        super.loadView()
        self.view = webview
        //设置代理
        webview.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        setupNavigation()
        // 使用WebView加载登录界面
        // GET, 在地址后面?参数1=值&参数2=值&参数3=值
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webview.loadRequest(request)
        // 显示加载
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        
        SVProgressHUD.showWithStatus("正在加载...")
    }
 //设置导航栏
    private  func  setupNavigation()
    {
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")

    self.navigationItem.title = "登录"
    
    }
 //自动填充账号
    @objc  private  func autoFill()
    {
        
        let jscode = "document.getElementById('userId').value='18664896947';document.getElementById('passwd').value='weibo178'"
        webview.stringByEvaluatingJavaScriptFromString(jscode)
    }
 //取消关闭控制器
    @objc  private  func close()
    {
    self.dismissViewControllerAnimated(true , completion: nil )
    
    }
    //懒加载
    private lazy  var webview:UIWebView = UIWebView()
}
extension   AVGOAuthViewController:UIWebViewDelegate
{
   //webview加载完成
    func  webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
   /// 每当WebView要去加载一个网页都会调用这个方法,询问我们是否真的要去加载, 返回: false 就不加载 返回true就去加载
    func  webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!.absoluteString
        print("加载的地址：\(url)")
        //其他的界面不需要拦截
        if !url.hasPrefix(redirect_uri)
        {
        // 不是授权回调地址, 放过,去加载
        return  true
        
        }else
        {
        let query = request.URL!.query!
        print("query:\(query)")
        // 判断query是否以code=开头
        let codeing = "code="
             if query.hasPrefix(codeing)
            {
                // 点击了授权
                print("点击了授权")
            let er = query  as NSString
            let code = er.substringFromIndex(codeing.characters.count)
            //print("截取到的code = \(code)")
            // 发送POSET请求获取AccessToken
   AVGUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code, completion: { (error: NSError?) -> Void in
                    // 网络失败也调用
    if error != nil {
    SVProgressHUD.showErrorWithStatus("加载AccessToken出错了")
      //延迟关闭了
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
        return
    }
    // 保存账号后会调用
    // 关闭控制器
    self.close()
   })
             } else {
                // 点击了取消
                // 直接关闭控制器
                self.close()
            }
            
            return false
        }
}
}
